package framework.dao.jdbc.util;

import framework.dao.exception.DataAccessException;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {

    private static Properties config;

    private static ThreadLocal<Connection> threadLocal;


    static{
        try {
            config=new Properties();
            threadLocal=new ThreadLocal<Connection>();

            config.load(JdbcUtil.class
                                .getClassLoader()
                                .getResourceAsStream("dataSource.properties"));


            Class.forName(config.getProperty("jdbc.driverClassName"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("JdbcUtil初始化失败");
        }
    }

    //一个事务一个连接，一个线程一个事务，一个线程一个连接
    //连接，线程单例
    public static Connection getConnection(){

        Connection con=threadLocal.get();
        if(con==null) {
            try {
                con = DriverManager.getConnection(config.getProperty("jdbc.url"),
                                                  config.getProperty("jdbc.username"),
                                                  config.getProperty("jdbc.password"));
                threadLocal.set(con);
            } catch (Exception e) {
                e.printStackTrace();
                throw new DataAccessException("数据访问失败", e);
            }
        }
        return con;
    }

    //关闭跟本线程相关的连接
    public static void close(){
        Connection con=threadLocal.get();
        if(con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            threadLocal.remove();
        }
    }

    public static void close(Connection con, PreparedStatement ps, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
